package com.zzx.schoolfellow.config;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.zzx.schoolfellow.common.api.ApiResult;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * @program: schoolfeoolw_backend
 * @description: 验证码
 * @author: zzx
 * @create: 2023-05-04 13:46
 **/
public class VerifyCode {
    private int width = 160;
    private int height = 40;
    private BufferedImage bufferedImage;
    private String code = "";
    private String string = "wertyupasdfhjkzxcvbnmQWERTYUPASDFGHJKLZXCVBNM0123456789";


    public String getCode() {
        return code;
    }

    public String getImg(){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "png",stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64 = Base64.encode(stream.toByteArray());
        try {
            stream.flush();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(base64);
        return "data:image/png;base64,"+base64;
    }
    public  VerifyCode(){
        bufferedImage = new BufferedImage(width,height,bufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g = bufferedImage.createGraphics();
        g.setColor(Color.white);
        g.fillRect(0,0,width,height);
        g.setColor(Color.black);
        g.drawRect(0,0,width-1,height-1);
        Random random = new Random();
        g.setFont(new Font("",Font.BOLD,25));
        for (int i = 1;i<=4;i++){
            double theta = Math.random()*Math.PI/4*((int)(Math.random()*2) == 0?1:-1);
            g.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
            g.rotate(theta,(width/4)*i-(width/8),28);
            char c = string.charAt(random.nextInt(string.length()));
            g.drawString(c+"",(width/4)*i-(width/8),28);
            code+=c;
            g.rotate(-theta,(width/4)*i-(width/8),28);
        }
        for (int i = 0; i < 10; i++) {
            g.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
            int x1=random.nextInt(width);
            int x2=random.nextInt(width);
            int y1=random.nextInt(height);
            int y2=random.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
    }
}
